const axios = require('axios');
const crypto = require('crypto');

const CENTER_URL = 'http://localhost:3000';

// 测试工具函数
async function uploadTestFile(filename, size) {
    const content = 'A'.repeat(size);
    const response = await axios.post(`${CENTER_URL}/upload`, {
        filename,
        content
    });
    return {
        ...response.data,
        actualContent: content
    };
}

async function downloadTestFile(filename) {
    const response = await axios.get(`${CENTER_URL}/download/${filename}`);
    return response.data;
}

// 主测试流程
async function runTests() {
    console.log('====================');
    console.log('开始分布式存储系统测试');
    console.log('====================\n');

    // 测试1：简单文件上传下载
    console.log('[测试1] 上传下载基础功能验证');
    const smallFile = await uploadTestFile('hello.txt', 500);
    console.log(`- 上传文件成功: ${smallFile.filename}, ${smallFile.shardCount} 个分片`);

    const downloadResult = await downloadTestFile('hello.txt');
    console.log(`- 下载文件成功: ${downloadResult.content === smallFile.actualContent ? '✓ 内容一致' : '✗ 内容不一致'}`);

    // 测试2：跨分片文件测试
    console.log('\n[测试2] 跨分片文件测试 (2KB)');
    const testFilename = 'large_file.txt';
    const largeFile = await uploadTestFile(testFilename, 2048); // 2KB (2 * 1024)
    console.log(`- 文件分片数: ${largeFile.shardCount} (预期: 2)`);
    console.log(`- 文件哈希: ${largeFile.fileHash}`);

    const largeFileDownload = await downloadTestFile(testFilename);
    console.log(`- 下载文件大小: ${largeFileDownload.content.length} (预期: 2048)`);
    console.log(`- 文件完整性: ${largeFileDownload.content === largeFile.actualContent ? '✓ 内容一致' : '✗ 内容不一致'}`);
}

// 错误处理
async function run() {
    try {
        await runTests();
    } catch (error) {
        console.error('!! 测试发生错误:', error.message);
        console.error('!! 请确保数据中心和存储节点已启动');
        console.error('!! 启动命令:');
        console.error('!!   node dataCenter.js');
        console.error('!!   node dataNode.js');
    }
}

// 执行测试
run();